import { nextTick, toRaw } from "vue";
import type { App, Plugin } from "vue";
const imageQueueList: {
  elem: HTMLImageElement;
  src: string;
  isLoaded: boolean;
}[] = [];
let container: HTMLElement | null = null;
/*
图片按需加载方法
- 计算图片是否在可视区域
- 如果在就进行按需加载
*/
function loadDisplayImage() {
  if (!container) {
    return;
  }
  const containerRect: DOMRect = container?.getBoundingClientRect() as DOMRect;
  // console.log(containerRect, "containerRect", imageQueueList);

  for (let i = 0; i < imageQueueList.length; i++) {
    const item = imageQueueList[i];
    // console.log(item, "item", i);

    if (item.isLoaded === true) {
      continue;
    }
    const rect = item.elem.getBoundingClientRect();

    const imageOffsetContainerTop = rect.y - containerRect.y;
    // console.log(
    //   rect,
    //   "rect",
    //   i,
    //   container?.clientHeight,
    //   imageOffsetContainerTop
    // );
    if (
      imageOffsetContainerTop > 0 &&
      imageOffsetContainerTop - 800 < container?.clientHeight //减800是为了有一个缓冲区域可以让在视口下面的一两张图片也能加载出来
    ) {
      item.elem.setAttribute("src", item.src);
      item.isLoaded = true;
    }
    // console.log(item, "item2", i);
  }
}
// 容器滚动事件
function handleWheelEvent() {
  loadDisplayImage();
}
// 监听可视容器的滚动事件
function listenScroll() {
  container?.addEventListener("wheel", handleWheelEvent);
}
// 图片懒加载插件
const LazyloadPlugin: Plugin = {
  install(app: App) {
    // 注册自定义图片懒加载命令
    app.directive("lazy-src", {
      beforeMount(el, binding) {
        // 收集所有需要懒加载的图片
        imageQueueList.push({
          elem: el as HTMLImageElement,
          src: toRaw(binding?.value) as unknown as string,
          isLoaded: false,
        });
      },
    });
    // 注册懒加载可视容器命令
    app.directive("lazy-container", {
      beforeMount(el) {
        console.log(el, "el");

        // 注册懒加载可视区间容器DOM
        container = el;
      },
    });
    nextTick(() => {
      if (container) {
        listenScroll();
        loadDisplayImage();
      }
    });
  },
};
export default LazyloadPlugin;
